import datetime
from django.views.decorators.cache import cache_page
from App.models import Statistics, Issues  # 导入要从应用包级别导入
from utils.utils import return_json, get_last_n_days_str, get_last_n_days


@cache_page(60 * 5)
def statistics(request):
    if request.method == "POST":  # 接受前端的浏览记录统计
        try:
            view_date = request.POST.get('view_date')
            delta = float(request.POST.get('delta'))  # 前端通过navigator.sendBeacon都是字符串值
            Statistics.objects.create(date=datetime.date(*map(int, view_date.split('-'))), delta=delta)
            return return_json({'code': 1000})
        except Exception as ex:
            print(ex)
            return return_json({'code': 1001, 'msg': str(ex)})
    if request.method == 'GET':  # 返回过去30天的访问数据
        last_30_days = get_last_n_days(30)
        dates = get_last_n_days_str(30)
        query_set = Statistics.objects.filter(date__gte=last_30_days[0], date__lte=last_30_days[-1])
        num = []
        for day in last_30_days:
            num.append(query_set.filter(date=day).count())
        return return_json({
            'code': 1000,
            'data': {
                'dates': dates,
                'num': num
            }
        })


def issue(request):
    if request.method == "POST":
        try:
            issue = request.POST.get('issue')
            Issues.objects.create(content=issue, time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            return return_json({'code': 1000})
        except Exception as ex:
            print(ex)
            return return_json({'code': 1001, 'msg': str(ex)})
    if request.method == "GET":
        obj = list(reversed(Issues.objects.all()))  # reversed使新评论在上
        res = {'code': 1000}
        total = len(obj)
        issues = []
        if total <= 50:
            for item in obj:
                temp = {'content': item.content, 'time': item.time.strftime('%Y-%m-%d %H:%M')}
                issues.append(temp)
        else:
            count = 1
            for item in obj:
                temp = {'content': item.content, 'time': item.time.strftime('%Y-%m-%d %H:%M')}
                issues.append(temp)
                count += 1
                if count > 50:
                    break
        res['issues'] = issues
        res['total'] = total
        return return_json(res)
